/********************************************************************
 * Copyright (c) 2004 Ultimania Organization. 
 * All rights reserved. This program and the accompanying materials 
 * are made available under the terms of the Eclipse Public License
 * v1.0 which accompanies this distribution, and is available at
 * http://www.eclipse.org/org/documents/epl-v10.html
 * 
 * Contributors:
 *     tidus - initial implementation. 
 *******************************************************************/

package org.ultimania.middlegenide.core;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.sql.Driver;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class JarClassLoader extends URLClassLoader {
	
	public JarClassLoader(URL url){
		super(new URL[]{url});
	}
	
	public JarClassLoader(URL[] urls){
		super(urls);
	}
	
	public void getJDBCDriverClass(List list, Class cls, Class org){
		Class[] interfaces = cls.getInterfaces();
		for(int i=0;i<interfaces.length;i++){
			interfaces[i].getInterfaces();
			if(interfaces[i].equals(Driver.class)){
				list.add(org);
			}
		}
		Class s = cls.getSuperclass();
		if(s!=null)getJDBCDriverClass(list, s ,org);
	}

	public List getJDBCDriverClass(String jarName) throws IOException, ClassNotFoundException {
		Package[] pkg = getPackages();
		if(jarName.equals(""))return new ArrayList();
		JarFile jarFile = new JarFile(jarName);
		Enumeration e = jarFile.entries();
		ArrayList list = new ArrayList();
		while(e.hasMoreElements()){
			JarEntry entry = (JarEntry)e.nextElement();
			String name = entry.getName();
			if(name.lastIndexOf(".class")!=-1){
				String ccls = name.replaceFirst(".class","").replaceAll("/",".");
				try {
				    Class cls = loadClass(ccls,true);
				    getJDBCDriverClass(list,cls ,cls);
				} catch (NoClassDefFoundError ex) {
				} catch (ClassNotFoundException ex) {
				}
			}
			
		}
		return list;
	}

}
